<template>
  <ContentWrap>
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="70"
    >
      <el-form-item label="中标客户" prop="customerId">
        <el-select
          v-model="queryParams.customerId"
          clearable
          filterable
          collapse-tags
          class="!w-200px"
          placeholder="请选择中标客户"
        >
          <el-option
            v-for="item in cusList"
            :key="item.id"
            :label="item.companyName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="产品类别" prop="coalId">
        <el-select
          v-model="queryParams.coalId"
          clearable
          filterable
          collapse-tags
          class="!w-200px"
          placeholder="请选择产品类别"
        >
          <el-option
            v-for="item in coalTypeList"
            :key="item.id"
            :label="item.coalName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="推送状态" prop="pushStatus">
        <el-select
          clearable
          v-model="queryParams.pushStatus"
          placeholder="请选择推送状态"
          class="!w-200px"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.PUSH_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="竞拍开始时间" label-width="100" prop="startTime">
        <el-date-picker
          v-model="queryParams.startTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          type="datetimerange"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-400px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" />
          重置
        </el-button>
        <el-button
          type="primary"
          plain
          @click="handlePush"
          v-hasPermi="['bidManage:pushJiLiang:push']"
        >
          一键推送
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>
  <ContentWrap>
    <!-- 列表 -->
    <el-table
      v-loading="loading"
      :data="list"
      border
      stripe
      ref="tableRef"
      :header-cell-style="{ background: '#F3F4F7', color: '#555' }"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="编号" align="center" prop="serialNum" width="60" fixed="left">
        <template #default="{ $index }">
          {{ $index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="中标客户" align="center" prop="customerName" min-width="150" fixed="left" />
      <el-table-column
        label="标段号"
        align="center"
        prop="markCode"
        min-width="200"
        fixed="left"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="推送状态" align="center" prop="pushStatus" width="100">
        <template #default="{ row }">
          {{getDictLabel(DICT_TYPE.PUSH_STATUS, row.pushStatus?.toString())}}
        </template>
      </el-table-column>

      <el-table-column label="产品类别" align="center" prop="coalName" width="150" />
      <el-table-column label="中标价格(元/吨)" align="center" prop="bidPrice" width="150" />
      <el-table-column label="中标量(吨)" align="center" prop="bidAmount" width="100" />
      <el-table-column label="关联客户" align="center" prop="relationCustomerName" min-width="150" :show-overflow-tooltip="true" />
      <el-table-column label="关联产品" align="center" prop="relationCoalName" width="120" />
      <el-table-column label="竞拍开始时间" align="center" prop="startTime" min-width="170" :formatter="dateFormatter"
                         :show-overflow-tooltip="true" />
      <el-table-column label="交货周期" align="center" prop="deliveryCycle" min-width="170"
                         :show-overflow-tooltip="true" />
      <el-table-column label="拉运时间" align="center" prop="transportTime" min-width="170"
                         :show-overflow-tooltip="true" />
      <el-table-column label="更新时间" align="center" prop="updateTime" min-width="170" :formatter="dateFormatter"
                         :show-overflow-tooltip="true" />
    </el-table>
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>
  <handlePushModel ref="handlePushModel" @success="handleSuccess"></handlePushModel>
</template>
<script setup lang="ts" name="mySubject">
import { DICT_TYPE, getDictLabel, getStrDictOptions } from '@/utils/dict'
import HandlePushModel from './HandlePushModel.vue'
import * as pushJiLiang from '@/api/pushJiLiang'
import {dateFormatter, formatDate} from '@/utils/formatTime'
import {initMonthTimeRange} from "@/utils/common";
import * as announceManage from "@/api/announceManage";
import * as dataCenter from "@/api/dataCenter";
import {ElTable} from "element-plus";

const loading = ref(true) // 列表的加载中
const exportLoading = ref(false) // 列表的加载中
const message = useMessage()
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const router = useRouter()
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  customerId: undefined,
  coalId: undefined,
  pushStatus: undefined,
  startTime: [
  formatDate(new Date(new Date().setHours(0, 0, 0, 0))),
  formatDate(new Date(new Date().setHours(23, 59, 59, 999)))
]
})

/** 获取客户列表 */
const cusList =ref()
const getCustomList = async () => {
  const data = await announceManage.getAllList()
  cusList.value = data || []
}
/** 获取产品列表 */
const coalTypeList: Record<string, any> = ref([])
const bidCoalManageList = async () => {
  const res = await dataCenter.bidCoalManageList()
  coalTypeList.value = res || []
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await pushJiLiang.getPushMeteringPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const queryFormRef = ref()
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

const handleSuccess = () => {
  getList()
}

const handlePushModel = ref()
const tableRef = ref<typeof ElTable>() // 表格的 Ref
/** 一键推送按钮操作 */
const handlePush = async() =>{
  await getRelationCustomer()
  let selectedDatas = tableRef.value.getSelectionRows()
  if(selectedDatas.length == 0){
    message.warning('请勾选标段！')
    return
  }
  if(selectedDatas.length > 100){
    message.warning('最大勾选100条数据！')
    return
  }
  // 校验是否是“待推送”状态
  const invalidStatus = selectedDatas.some(row => row.pushStatus !== 0)
  if (invalidStatus) {
    message.warning('请勾选状态为待推送的标段！')
    return
  }
  // 获取第一个数据的 customerId 和 coalId 作为基准
  const baseCustomerId = selectedDatas[0].customerId
  const baseCoalId = selectedDatas[0].coalId
  // 校验是否所有数据都为同一客户、同产品
  const notSameCustomerOrCoal = selectedDatas.some(
    row => row.customerId !== baseCustomerId || row.coalId !== baseCoalId
  )

  if (notSameCustomerOrCoal) {
    message.warning('请选择同一客户的同煤种标段！')
    return
  }
  handlePushModel.value.open(selectedDatas,relCusList.value)
}
/** 获取关联客户列表 */
const relCusList =ref()
const getRelationCustomer = async () => {
  const data = await pushJiLiang.getRelationCustomer()
  relCusList.value = data || []
}
/** 初始化 **/
onMounted(() => {
  getCustomList()
  bidCoalManageList()
  getList()
})

defineExpose({})
</script>
